package com.example.user1.service.impl;

import com.example.user1.common.RedisCommon;
import com.example.user1.enums.ErrorEnum;
import com.example.user1.enums.VerifyCodeTypeEnum;
import com.example.user1.exception.BusinessException;
import com.example.user1.util.IdUtils;
import com.example.user1.util.RedisImageCaptchaUtil;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RandomIdGenerator;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;

import static com.example.user1.common.RedisCommon.PHONE_CODE;

@Service
@RequiredArgsConstructor
@Slf4j
public class VerifyCodePhoneServiceImpl extends VerifyCodeServiceImpl {
    private final RedissonClient redissonClient;
    private final static Integer codeSize = 6;

    @Override
    public void generate(String phone) {
        // 发送短信
        // 存储手机号和验证码关系
        RMap<String, String> map = redissonClient.getMap(PHONE_CODE);
        String code = IdUtils.randomNum(6);
        log.info("手机号：{},验证码：{}", phone, code);
        map.put(phone, code);
    }

    public boolean match(@NotNull String phone, @NotEmpty String code) {
        if (code.length() != codeSize) {
            return false;
        }
        Map<String, String> map = redissonClient.getMap(PHONE_CODE);
        String oldCode = map.get(phone);
        if (!StringUtils.hasText(oldCode) && !Objects.equals(oldCode, code))
            throw new BusinessException(ErrorEnum.VERIFICATION_CODE_EXPIRED);

        return true;
    }

    @Override
    public VerifyCodeTypeEnum type() {
        return VerifyCodeTypeEnum.PHONE;
    }
}
